package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
public class StorageTccActionImpl implements StorageTccAction {
    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
        log.info("减少商品库存，第一阶段，锁定减少的库存量，productId=" + productId + "， count=" + count);
        Storage storage = storageMapper.selectById(productId);
        if (storage.getResidue() - count < 0) {
            throw new RuntimeException("库存不足!");
        }

        /*
        库存减掉count， 冻结库存增加count
         */
        storageMapper.updateResidueToFrozen(productId, count);

        //保存标识
        ResultHolder.setResult(getClass(), ctx.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext ctx) { //加synchronized锁  保证在提交时遇到阻塞时,第二次发送提交请求时,保证两次提交请求不重复删除标记
        // Long productId = Long.valueOf(ctx.getActionContext("productId").toString()); 也还可用转成Long对象
        long productId = Long.parseLong(ctx.getActionContext("productId").toString());
        int count = Integer.parseInt(ctx.getActionContext("count").toString());
        log.info("减少商品库存，第二阶段提交，productId=" + productId + "， count=" + count);

        //防止重复提交
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            return true;
        }
        storageMapper.updateFrozenToUsed(productId, count);

        //删除标识
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext ctx) {
        // Long productId = Long.valueOf(ctx.getActionContext("productId").toString()); 也还可用转成Long对象
        long productId = Long.parseLong(ctx.getActionContext("productId").toString());
        int count = Integer.parseInt(ctx.getActionContext("count").toString());
        log.info("减少商品库存，第二阶段，回滚，productId=" + productId + "， count=" + count);


        //防止重复回滚
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            return true;
        }
        storageMapper.updateFrozenToResidue(productId, count);


        //删除标识
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;
    }
}
